package com.kaver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.kaver.dao.po.OrderInfo;
import com.kaver.dao.po.UserInfo;
import com.kaver.dao.service.OrderInfoDao;
import com.kaver.dao.service.UserInfoDao;

@RestController
public class TestController {
	@Autowired
	UserInfoDao userInfoDao;
	@Autowired
	OrderInfoDao orderInfoDao;
	
	@GetMapping("/saveUser")
	public JSONObject getConfig(@RequestParam("ds") String ds) {
		DynamicDataSourceContextHolder.push(ds);
		try {
			UserInfo userInfo = new UserInfo();
			userInfo.setName("张 " + Math.random());
			userInfoDao.save(userInfo);
			return (JSONObject) JSON.toJSON(userInfo);
		} finally {
			DynamicDataSourceContextHolder.poll();
		}
		
	}
	
	@GetMapping("/saveOrder")
	public JSONObject saveOrder(@RequestParam("ds") String ds) {
		DynamicDataSourceContextHolder.push("sharding-"+ ds);
		try {
			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setName("张 " + Math.random());
			orderInfoDao.save(orderInfo);
			return (JSONObject) JSON.toJSON(orderInfo);
		} finally {
			DynamicDataSourceContextHolder.poll();
		}
		
	}
	@GetMapping("/queryUser")
	public JSONArray queryUser(@RequestParam("ds") String ds) {
		DynamicDataSourceContextHolder.push(ds);
		try {
			return (JSONArray) JSON.toJSON(userInfoDao.list());
		} finally {
			DynamicDataSourceContextHolder.poll();
		}
	}
	@GetMapping("/queryOrder")
	public JSONArray queryOrder(@RequestParam("ds") String ds) {
		DynamicDataSourceContextHolder.push("sharding-"+ ds);
		try {
			return (JSONArray) JSON.toJSON(orderInfoDao.list());
		} finally {
			DynamicDataSourceContextHolder.poll();
		}
	}
}
